/*
 * 文 件 名 : DolphinService.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-9-26
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.fire8.dolphin.db.ChatDAO;
import com.fire8.dolphin.db.FriendDAO;
import com.fire8.dolphin.model.ChatRecord;
import com.fire8.dolphin.model.Friend;
import com.fire8.dolphin.service.xmpp.EventTypes;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.MainActivity;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.chat.ChatActivity;
import com.fire8.dolphin.ui.chat.FriendActivity;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.MD5;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * <一句话功能简介><br>
 * <功能详细描述>
 *
 * @author  lixg
 * @version [版本号,2012-9-26]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class DolphinService extends Service
{
    Context context;
    JaberClientService service;
    
    DolphinApplication app;
    
    private FriendDAO friendDao;
    private ChatDAO chatDao;
    /**
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
    
    @Override
    public void onCreate()
    {
        
        super.onCreate();
        LogUtil.d("DolphinService 已启动");
        context = getApplicationContext();
        service = JaberClientService.getInstance();
        service.setHandler(mHandler);
        friendDao = new FriendDAO(context);
        chatDao = new ChatDAO(context);
        app = (DolphinApplication)getApplication();
        //loginServer();
        
    }

    
    
    @Override
    public void onStart(Intent intent, int startId)
    {
        LogUtil.d("DolphinService on start");
        super.onStart(intent, startId);
        if(!service.isConnected())
        {
            LogUtil.d("连接服务器");
            new LoginTask().execute("");
        }
    }

    private final Handler mHandler = new Handler()
    {
        
        @Override
        public void handleMessage(Message msg)
        {
            
            super.handleMessage(msg);
            final Presence presence;
            switch (msg.what)
            {
            
                case EventTypes.ADD_FRIEND_REFUSED://添加人家为好友，被拒绝，丢脸啊
                    presence = (Presence) msg.obj;
                    //对方把你从好友列表里删除
                    Toast.makeText(context, presence.getFrom()+"拒绝了你的好友请求", Toast.LENGTH_LONG).show();
                    break;
                case EventTypes.BE_ADD_FRIEND://对方请求加为好友
                    //service里不能用系统的context弹出窗口，所以改为用启动Activity的方式
                    
                    presence= (Presence) msg.obj;
                    /** 取消加好友功能，不需要加好友也可以聊天 2012-10-22
                    //Toast.makeText(context, presence.getFrom()+"添加你为好友", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(context,AddFriendActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("from", splitAccount(presence.getFrom()));
                    startActivity(intent);
                    */
                    LogUtil.d("对方请求加为好友:"+presence.getFrom());
                    //主动加对方为好友 2012-11-3 加为好友的好处是可以监听对方是否在线
                    addFriend(presence.getFrom());
                    break;
                case EventTypes.ADD_FRIEND_ED://对方同意加为好友
                    //取消加好友功能，不需要加好友也可以聊天 2012-10-22
//                    try
//                    {
//                        presence = (Presence) msg.obj;
//                        LogUtil.d("对方同意加为好友,我的userId:"+app.getUserId());
//                        LogUtil.d("对方friendAccount: "+presence.getFrom());
//                        
//                        List<NameValuePair> param = new ArrayList<NameValuePair>();
//                        param.add(new BasicNameValuePair("userId",app.getUserId()));
//                        //param.add(new BasicNameValuePair("friendUserId",splitAccount(presence.getFrom())));
//                        param.add(new BasicNameValuePair("friendAccount",splitAccount(presence.getFrom())));
//                        String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"user/addFriend.php", param);
//                        LogUtil.d(json);
//                        
//                    }
//                    catch (Exception e)
//                    {
//                        LogUtil.e("" ,e);
//                        break;
//                    }
//                    //将好友写到本地数据库
//                    try
//                    {
//                        LogUtil.d("同步好友");
//                        //同步好友
//                        List<NameValuePair> param = new ArrayList<NameValuePair>();
//                        param.add(new BasicNameValuePair("userId",app.getUserId()));
//                        RequestUtils.getInstall().getUserListByAccounts(param,friendDao);
//                        //发送广播通知页面刷新
//                        Intent intent2 = new Intent();
//                        intent2.setAction("com.fire8.dolphin.ui.FriendActivity");
//                        sendBroadcast(intent2);
//                    }
//                    catch (Exception e)
//                    {
//                        LogUtil.e("同步好友失败", e);
//                        
//                    }
                    break;
                case EventTypes.CHAT_MSG://聊天信息
                    org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message)msg.obj;
                    String account = splitAccount(message.getFrom());
                    LogUtil.d("收到聊天信息");
                    LogUtil.d("收到来自["+account+"]的信息["+message.getBody()+"]");
                    //将数据写入数据库
                    ChatRecord cr = new ChatRecord();
                    //cr.setUserId(Integer.valueOf(userId));
                    cr.setAccount(account);
                    cr.setItemIO(ChatRecord.ITEM_IO_IN);
                    cr.setItemType(ChatRecord.ITEM_TYPE_TEXT);
                    cr.setChatItem(message.getBody());
                    cr.setChatDate(DateUtil.dateToStr(new Date(),
                            "yyyy-MM-dd HH:mm:ss"));
                    chatDao.add(cr);
                    //LogUtil.d("保存聊天记录");
                    //检查对方是否为自己好友，如果不是，则新增加好友
                    Friend friend = new Friend();
                    friend.setAccount(account);
                    List<HashMap<String, String>> list = friendDao.findList(friend);
                    if(list.isEmpty())
                    {
                        addFriend(message.getFrom());
                    }
                    
                    //收到消息，检查聊天窗口是否打开，并且聊天对象是该好友，则广播更新
                    //如果聊天窗口没打开，则检查好友列表是否打开，如果是则给收到消息的好友加上new 标签
                    //如果好友列表也没打开，则检查主窗口有没有打开，如果打开，则在“会话”按钮显示new 标签，否则，用通知栏消息通知用户
                    
                    Intent intent2 = new Intent();
                    intent2.setAction("com.fire8.dolphin.ui.ChatActivity");
                    intent2.putExtra("account", account);
                    
                    if(ChatActivity.isOpen() && account.equals(ChatActivity.getCurrertAccount()))
                    {
                        
                        //发送广播通知页面刷新
                        
                        sendBroadcast(intent2);
                        //LogUtil.d("聊天窗口打开，发送广播");
                    }else if(FriendActivity.isOpen())
                    {
                        // 修改好友表字段hasMsg字段，表示有新消息
                        friendDao.hasMsg(account, 1);
                        LogUtil.d("修改好友的状态为有新消息:"+account);
                        //发送广播通知页面刷新
                        sendBroadcast(intent2);
                        
                    }else if(MainActivity.isOpen())
                    {
                        //发送广播通知页面刷新
                        friendDao.hasMsg(account, 1);
                        LogUtil.d("修改好友的状态为有新消息:"+account);
                        sendBroadcast(intent2);
                        
                    }
                    else
                    {
                        friendDao.hasMsg(account, 1);
                        LogUtil.d("修改好友的状态为有新消息:"+account);
                        //在状态栏上通知
                        Intent mIntent = new Intent(context,ChatActivity.class);  
                        mIntent.putExtra("account", account);
                        //这里需要设置Intent.FLAG_ACTIVITY_NEW_TASK属性  
                        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);      
                        PendingIntent mContentIntent =PendingIntent.getActivity(context,0, mIntent, 0);  
                        //这里必需要用setLatestEventInfo(上下文,标题,内容,PendingIntent)不然会报错.  
                        Notification notification = new Notification(R.drawable.logo,message.getBody(),System.currentTimeMillis());  
                        notification.setLatestEventInfo(context, account, message.getBody(), mContentIntent);  
                        notification.defaults = Notification.DEFAULT_LIGHTS;
                        notification.ledARGB = 0xff00ff00;
                        notification.ledOnMS = 300;
                        notification.ledOffMS = 1000;
                        notification.flags = Notification.FLAG_SHOW_LIGHTS;
                        //这里发送通知(消息ID,通知对象)  
                        NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
                        mNotificationManager.notify(account.hashCode(), notification); 
                    }
                    break;
            }
        }

        /**
         * 添加对方为好友
         * <功能详细描述>
         * @param presence [参数说明]
         *
         * @author lixg
         * @see [类、类#方法、类#成员]
         */
        private void addFriend(final String from)
        {
            service.responseToAddFriend( from, true);
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("userId",app.getUserId()));
            //param.add(new BasicNameValuePair("friendUserId",splitAccount(presence.getFrom())));
            param.add(new BasicNameValuePair("friendAccount",splitAccount(from)));
            String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"user/addFriend.php", param);
            LogUtil.d(json);
            try
            {
                LogUtil.d("同步好友");
                //同步好友
                param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("userId",app.getUserId()));
                RequestUtils.getInstall().findFriendList(param,friendDao);
                //发送广播通知页面刷新
                Intent intent2 = new Intent();
                intent2.setAction("com.fire8.dolphin.ui.FriendActivity");
                sendBroadcast(intent2);
            }
            catch (Exception e)
            {
                LogUtil.e("同步好友失败", e);
            }
        }
    };
    
    private String splitAccount(String fid)
    {
        if(StringUtil.isEmpty(fid))
        {
            return null;
        }
        String[] strings = fid.split("@");
        if(strings.length>1)
        {
            return strings[0];
        }
        return null;
    }
    
    class LoginTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            loginServer();
            return null;
        }
        
    }
    
    /**
     * 登录服务器
     * <功能详细描述> [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void loginServer()
    {
        if(!RequestUtils.getInstall().isConnect(context))
        {
            return;
        }
        String account = app.getAccount();
        String password = app.getPassword();
        if (!StringUtil.isEmpty(account))
        {
            //如果是已注册用户，则登录服务器
            try
            {
                service.connect();
                service.login(account, password);
                LogUtil.d("用户登录:"+account);
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("account", account));
                param.add(new BasicNameValuePair("password", MD5.code(password)));
                String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL
                        + "user/login.php", param);
                //设置用户ID
                if(StringUtil.isEmpty(json))
                {
                    throw new Exception("登录失败");
                }
                
                JSONObject data = new JSONObject(json);
                String msgCode = data.getString("msgCode");
                //String desc = data.getString("desc");
                if("1".equals(msgCode))
                {
                    JSONObject object = data.getJSONObject("msgBody");
                    
                    //将用户ID写入本地
                    app.setUserId(object.getString("userId"));
                }else
                {
                    throw new Exception(data.getString("desc"));
                }
                
            }
            catch (XMPPException e)
            {
                LogUtil.e("连接openfire服务器失败", e);
            }
            catch (Exception e)
            {
                service.disConn();
                LogUtil.e("连接openfire服务器失败", e);
            }
        }else
        {
            LogUtil.d("签到，获取userId:"+app.getUserId());
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //收集用户信息，比如：电话号码、MAC码
            String tel = tm.getLine1Number();
            String location=null;
            //获取所在地
            try
            {
                LbsService lbsService = new LbsService(tm);
                location = lbsService.getLocation();
                
            }
            catch (Exception e)
            {
                LogUtil.e("",e);
            }
            //如果未注册，则去服务器签到
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("userId", app.getUserId()));
            param.add(new BasicNameValuePair("mac", getMacAddress()));
            param.add(new BasicNameValuePair("location",location));
            param.add(new BasicNameValuePair("tel",tel));
            //param.add(new BasicNameValuePair("ip", getLocalIpAddress()));
            String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+ "user/checkin.php", param);
            LogUtil.d("签到===="+json);
            if(!StringUtil.isEmpty(json))
            {
                try
                {
                    JSONObject data = new JSONObject(json);
                    String msgCode = data.getString("msgCode");
                    String userId = data.getString("msgBody");
                    if("1".equals(msgCode) && !StringUtil.isEmpty(userId))
                    {
                        app.setUserId(userId);
                        LogUtil.d("签到成功，返回userId:"+userId);
                    }
                }
                catch (Exception e)
                {
                    LogUtil.e("",e);
                }
            }
        }
    }
    /**获取MAC地址**/
    private String getMacAddress()
    {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }
}
